# coding:utf-8
# @作者：州的先生
# @公众号：zmister2016
# @名称：休息助手

from PyQt5 import QtWidgets,QtCore,QtGui
from configparser import ConfigParser,RawConfigParser
import datetime
import sys
import os


# 设置面板
class MainPanel(QtWidgets.QWidget):
    def __init__(self):
        super(MainPanel, self).__init__()
        self.setWindowTitle("电脑休息助手 v0.1 - 州的先生")
        self.setWindowIcon(QtGui.QIcon("./icon.png"))
        self.cycle_list = ['1','20','30','40','50','60']

        self.tips_cycle_secound = 1000 # 间隔秒数
        self.tips_rest_secound = 1000 # 休息秒数
        self.tips_status = False # 状态

        # 控制开关
        self.switch_label = QtWidgets.QLabel("状态：")
        self.switch_radio_en = QtWidgets.QRadioButton("开启")
        self.switch_radio_dis = QtWidgets.QRadioButton("关闭")
        # 休息周期
        self.rest_label = QtWidgets.QLabel("休息周期：")
        self.rest_txt_1 = QtWidgets.QLabel("每")
        self.rest_cycle_input = QtWidgets.QComboBox()
        self.rest_cycle_input.addItems(self.cycle_list)
        self.rest_txt_2 = QtWidgets.QLabel("分钟，休息")
        self.rest_time_input = QtWidgets.QLineEdit()
        self.rest_time_input.setValidator(QtGui.QIntValidator(1,999))
        self.rest_txt_3 = QtWidgets.QLabel("分钟")
        # 距离下一轮休息文本
        self.next_label = QtWidgets.QLabel("下次休息：")
        self.next_time_label = QtWidgets.QLabel("")
        # 保存
        self.save_btn = QtWidgets.QPushButton("保存")
        self.save_btn.clicked.connect(self.save_config)

        # 添加到布局层
        self.main_layout = QtWidgets.QGridLayout()
        ## 启用状态
        self.main_layout.addWidget(self.switch_label,0,0,1,1)
        self.main_layout.addWidget(self.switch_radio_en, 0, 1, 1, 1)
        self.main_layout.addWidget(self.switch_radio_dis, 0, 2, 1, 1)
        # 运行周期
        self.main_layout.addWidget(self.rest_label,1,0,1,1)
        self.main_layout.addWidget(self.rest_txt_1, 1, 1, 1, 1)
        self.main_layout.addWidget(self.rest_cycle_input, 1, 2, 1, 1)
        self.main_layout.addWidget(self.rest_txt_2, 1, 3, 1, 1)
        self.main_layout.addWidget(self.rest_time_input, 1, 4, 1, 1)
        self.main_layout.addWidget(self.rest_txt_3, 1, 5, 1, 1)
        # 下次休息倒计时
        self.main_layout.addWidget(self.next_label, 2, 0, 1, 1)
        self.main_layout.addWidget(self.next_time_label, 2, 1, 1, 1)
        # 保存
        self.main_layout.addWidget(self.save_btn, 3, 0, 1, 1)
        self.setLayout(self.main_layout)

        self.reay_config()
        self.timer_config()
        self.tray_config()

    # 读取配置文件
    def reay_config(self):
        CONFIG = ConfigParser()
        CONFIG.read(os.path.join('./config.ini'), encoding='utf-8')
        # 启用状态
        is_enable = CONFIG.get('status', 'is_enable', fallback='false')
        if is_enable == 'true':
            self.switch_radio_en.setChecked(True)
            self.switch_radio_dis.setChecked(False)
            self.tips_status = True
        else:
            self.switch_radio_en.setChecked(False)
            self.switch_radio_dis.setChecked(True)
            self.tips_status = False
        # 轮询周期
        cycle_time = CONFIG.get('cycle', 'cycle_time', fallback='30')
        if cycle_time in self.cycle_list:
            self.rest_cycle_input.setCurrentIndex(self.cycle_list.index(cycle_time))
            self.tips_cycle_secound = int(cycle_time) * 60
        else:
            self.rest_cycle_input.setCurrentIndex(0)
            self.tips_cycle_secound = 20 * 60

        # 休息时间
        rest_time = CONFIG.get('cycle', 'rest_time', fallback='3')
        self.rest_time_input.setText(rest_time)
        self.tips_rest_secound = int(rest_time) * 60

    # 托盘配置
    def tray_config(self):
        self.openAction = QtWidgets.QAction("打开", self)
        self.openAction.triggered.connect(self.showNormal)
        self.quitAction = QtWidgets.QAction("退出", self)
        self.quitAction.triggered.connect(self.quit)

        self.trayIconMenu = QtWidgets.QMenu(self)
        self.trayIconMenu.addAction(self.openAction)
        self.trayIconMenu.addAction(self.quitAction)

        self.trayIcon = QtWidgets.QSystemTrayIcon(self)
        self.trayIcon.setContextMenu(self.trayIconMenu)
        self.trayIcon.setIcon(QtGui.QIcon("./icon.png"))
        self.trayIcon.setToolTip("休息助手")
        self.trayIcon.show()

    # 计时器
    def timer_config(self):
        self.tips_widget = Tips(secound=self.tips_rest_secound)

        self.cycle_timer = QtCore.QTimer()
        self.cycle_timer.setInterval(1000)
        self.cycle_timer.start()
        self.cycle_timer.timeout.connect(self.cycle_timer_timeout)

    # 保存配置
    def save_config(self):
        try:
            # 启用状态
            is_enable = self.switch_radio_en.isChecked()
            if is_enable:
                self.tips_status = True
                is_enable = 'true'
            else:
                self.tips_status = False
                is_enable = 'false'
            # 周期
            cycle_time = self.rest_cycle_input.currentText()

            # 休息时间
            rest_time = self.rest_time_input.text()

            if int(cycle_time) * 60 < int(rest_time) * 60:
                QtWidgets.QMessageBox.warning(self, '错误', '间隔时间不得小于休息时间')
            else:
                CONFIG = ConfigParser()
                CONFIG.read(os.path.join('./config.ini'), encoding='utf-8')
                CONFIG.set('status','is_enable',is_enable)
                CONFIG.set('cycle', 'cycle_time', cycle_time)
                CONFIG.set('cycle', 'rest_time', rest_time)
                with open('./config.ini','w+') as file:
                    CONFIG.write(file)

                self.tips_rest_secound = int(rest_time) * 60
                self.tips_cycle_secound = int(cycle_time) * 60
                QtWidgets.QMessageBox.information(self,'成功','保存成功')
        except:
            QtWidgets.QMessageBox.warning(self,'失败','保存异常')

    # 计时器超时信号
    def cycle_timer_timeout(self):
        if (self.tips_status) and \
                (self.tips_cycle_secound == 0) and \
                (self.tips_widget.isHidden()):
            self.tips_widget.secound = self.tips_rest_secound
            self.tips_widget.timer_time.start()
            self.tips_widget.showFullScreen()
            self.tips_cycle_secound = int(self.rest_cycle_input.currentText()) * 60 + int(self.rest_time_input.text()) * 60
        elif self.tips_status and self.tips_cycle_secound > 0:
            print("当前周期：",self.tips_cycle_secound)
            print("休息时间：",self.tips_rest_secound)
            self.tips_cycle_secound -= 1
            if (self.tips_cycle_secound / 60) > 1:
                self.next_time_label.setText("{}分钟后".format(round(self.tips_cycle_secound /60,1)))
            else:
                self.next_time_label.setText("{}秒后".format(self.tips_cycle_secound))
        print(self.tips_cycle_secound)

    # 退出
    def quit(self):
        QtWidgets.QApplication.quit()


# 提示框
class Tips(QtWidgets.QMainWindow):
    def __init__(self,secound = 1000):
        super(Tips, self).__init__()
        self.secound = secound

        # 倒计时文本
        self.timer_lable = QtWidgets.QLabel("倒计时：00:00:00")
        self.timer_lable.setAlignment(QtCore.Qt.AlignCenter)
        self.timer_lable.setFont(QtGui.QFont('微软雅黑',30))
        self.timer_lable.setStyleSheet('''
            font-weight:900;
            color:white;
        ''')
        # 当前时间文本
        self.datetime_label = QtWidgets.QLabel("2020-02-02 02:20:20")
        self.datetime_label.setAlignment(QtCore.Qt.AlignCenter)
        self.datetime_label.setStyleSheet('''
            font-size:30px;
            color:white;
            font-weight:700;
            font-family:sans-serif;
        ''')
        # 提示文字
        self.tall_text = QtWidgets.QLabel("眼睛累了，起身远眺，活动筋骨，休息一下吧")
        self.tall_text.setFont(QtGui.QFont('微软雅黑',20))
        self.tall_text.setAlignment(QtCore.Qt.AlignCenter)
        self.tall_text.setStyleSheet('''
            color:white;
            font-weight:700;
        ''')
        # 退出按钮
        self.quit_btn = QtWidgets.QPushButton("结束休息")
        self.quit_btn.setFont(QtGui.QFont('微软雅黑',20))
        self.quit_btn.clicked.connect(self.stop_rest)
        self.quit_btn.setStyleSheet('''
            background-color:#f44545;
            color:white;
        ''')

        self.main_layout = QtWidgets.QGridLayout()
        self.main_layout.addWidget(self.timer_lable,0,0)
        self.main_layout.addWidget(self.tall_text, 1, 0)
        self.main_layout.addWidget(self.datetime_label,2,0)
        self.main_layout.addWidget(self.quit_btn,3,0)

        # 实时时间计时器
        self.datetime = QtCore.QTimer()  # 实例化一个计时器
        self.datetime.setInterval(1000)  # 设置计时器间隔1秒
        self.datetime.start()  # 启动计时器
        self.datetime.timeout.connect(self.show_datetime_slots)  # 计时器连接到槽函数更新UI界面时间
        # 倒计时计时器
        self.timer_time = QtCore.QTimer()  # 实例化一个计时器
        self.timer_time.setInterval(1000)
        # self.timer_time.start()
        self.timer_time.timeout.connect(self.show_timer_slots)

        self.main_widget = QtWidgets.QWidget()
        self.main_widget.setLayout(self.main_layout)
        self.setCentralWidget(self.main_widget)
        self.setWindowOpacity(1) # 设置窗口透明度
        # self.setAttribute(QtCore.Qt.WA_TranslucentBackground) # 设置窗口背景透明
        self.setWindowFlag(QtCore.Qt.FramelessWindowHint) # 隐藏边框

        self.setStyleSheet('''
            background-color:#333;
        ''')

    # 实时显示当前时间
    def show_datetime_slots(self):
        self.datetime_label.setText(datetime.datetime.strftime(datetime.datetime.today(), "%Y-%m-%d %H:%M:%S"))

    # 实时显示倒计时
    def show_timer_slots(self):
        try:
            if self.secound == 0:
                self.timer_time.stop()
                self.close()
            else:
                self.secound -= 1
                m, s = divmod(self.secound, 60)
                h, m = divmod(m, 60)
                print("%02d:%02d:%02d" % (h, m, s))
                self.timer_lable.setText("倒计时：%02d:%02d:%02d" % (h, m, s))
        except Exception as e:
            print(repr(e))

    # 结束休息
    def stop_rest(self):
        self.secound = 0
        self.close()


def main():

    app = QtWidgets.QApplication(sys.argv)
    QtWidgets.QApplication.setQuitOnLastWindowClosed(False)
    gui = MainPanel()
    gui.show()
    # gui = Tips()
    # gui.showFullScreen()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()